<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purpose">
              <j-dict-select-tag
                v-model="model.purpose"
                placeholder="请选择新增类型"
                dict-code="project_type"
                @change="handleChangePurpose"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.purpose">
            <a-form-model-item label="父节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pid">
              <a-select @change="handleChange" v-model="model.pid" v-if="model.purpose == 1">
                <a-select-option v-for="item in pidList" :key="item.id">
                  {{ item.caseName }}
                </a-select-option>
              </a-select>
              <a-cascader :options="options" placeholder="请选择" @change="changePid" v-if="model.purpose == 2" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="caseName">
              <a-input v-model="model.caseName" placeholder="请输入名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="简述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="caseVersion">
              <a-input v-model="model.caseVersion" placeholder="请输入简述"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="测试人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="testuser">
              <a-input v-model="model.testuser" placeholder="请输入测试人员"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="testOrg">
              <a-input v-model="model.testOrg" placeholder="请输入来源"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.purpose == 2">
            <a-form-model-item label="py文件地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="filePy">
              <a-input v-model="model.filePy" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.purpose == 2">
            <a-form-model-item label="yml文件地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileYml">
              <a-input v-model="model.fileYml" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'TestUserCaseForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      pidList: [],
      confirmLoading: false,
      validatorRules: {},
      url: {
        list: '/testUserCase/list',
        treelist: '/testUserCase/queryAllCase',
        add: '/testUserCase/add',
        edit: '/testUserCase/edit',
        queryById: '/testUserCase/queryById'
      },
      dataSource: [],
      dataTree: []
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    options() {
      // 1. 去掉 purpose === 0 的节点
      const validRoots = this.dataTree

      // 2. 仅保留两层
      return validRoots.map(node => ({
        value: node.id,
        label: node.caseName,
        // 如果还有子节点，也只放一层
        children: (node.children || [])
          .filter(c => c.purpose !== 0) // 如子节点也要过滤
          .map(c => ({
            value: c.id,
            label: c.caseName
            // 不再继续嵌套 children，级联到此为止
          }))
      }))
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    changePid(value) {
      this.model.pid = value[1]
    },
    handleChange() {},
    add(type) {
      this.edit(this.modelDefault, type)
    },
    edit(record, type) {
      this.getList()
      this.model = Object.assign({}, record)
      this.visible = true
      console.log(type, '111')
      if (type == 1) {
        this.model.purpose = 1
        // 确保数据加载完成后再设置父节点列表
        this.$nextTick(() => {
          this.handleChangePurpose(1)
        })
      } else {
        this.model.purpose = 2
        this.handleChangePurpose(type)
      }
    },
    updatePidList() {
      // 从树形数据中获取所有 purpose=0 的节点（目录节点）
      const getAllDirectoryNodes = nodes => {
        let directoryNodes = []
        nodes.forEach(node => {
          if (node.purpose === 0) {
            directoryNodes.push({
              id: node.id,
              caseName: node.caseName
            })
          }
          if (node.children && node.children.length > 0) {
            directoryNodes = directoryNodes.concat(getAllDirectoryNodes(node.children))
          }
        })
        return directoryNodes
      }

      this.pidList = getAllDirectoryNodes(this.dataTree)
      console.log('父节点列表:', this.pidList)

      if (this.pidList.length === 0) {
        console.warn('没有找到可用的目录节点作为父节点')
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log(this.model, 'handleChange')
          // return
          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    getList() {
      // 同时获取列表数据和树形数据
      Promise.all([getAction(this.url.list, {}), getAction(this.url.treelist, {})])
        .then(([listRes, treeRes]) => {
          if (listRes.success) {
            this.dataSource = listRes.result.records || []
            console.log('列表数据:', this.dataSource)
          } else {
            console.error('获取列表数据失败:', listRes)
          }

          if (treeRes.success) {
            this.dataTree = treeRes.result || []
            console.log('树形数据:', this.dataTree)

            // 数据加载完成后，如果当前是测试项类型，更新父节点列表
            if (this.model.purpose === 1) {
              this.updatePidList()
            }
          } else {
            console.error('获取树形数据失败:', treeRes)
          }
        })
        .catch(error => {
          console.error('获取数据失败:', error)
        })
    },

    handleChangePurpose(type) {
      console.log(type, '过滤不')
      if (type == 1) {
        // 类型为测试项时，更新父节点列表
        this.updatePidList()
      } else {
        // 类型为测试用例时，清空父节点选择
        this.model.pid = undefined
      }
    }
  }
}
</script>
